﻿using System.Xml;
using System.Windows.Forms;
using System;

namespace AutoMerge
{
    public class UpdateRoleManifest
    {
        public static void update(string filePath, string env, RichTextBox tb)
        {
            try
            {
                tb.AppendText("\r\n");
                tb.AppendText(@"updating RoleManifest file--------------------------------------------------------------" + "\r\n");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(filePath);

                //set <add key="DeliveryPort" value="8081"></add> to 80
                tb.AppendText("configuring node:  DeliveryPort" + "\r\n");
                XmlNode xn = xmldoc.SelectSingleNode("configuration/roles/role/settings/add[@key='DeliveryPort']");
                ((XmlElement)xn).SetAttribute("value", "80");

                //<add key="environment" value="0"></add> to 1
                tb.AppendText("configuring node:  environment" + "\r\n");
                xn = xmldoc.SelectSingleNode("configuration/roles/role/settings/add[@key='environment']");
                ((XmlElement)xn).SetAttribute("value", "1");

                //add key="WorkbenchDataServer" value="msnbc-v-%_UserAliasForMachineName%3"></add> 
                //to <add key="WorkbenchDataServer" value="RR1NBCSYSXSQL1\INST_WB"></add>
                tb.AppendText("configuring node:  WorkbenchDataServer" + "\r\n");
                env = "rr1nbc" + env + @"sql1\inst_wb";
                xn = xmldoc.SelectSingleNode("configuration/roles/role/settings/add[@key='WorkbenchDataServer']");
                ((XmlElement)xn).SetAttribute("value", env);

                xmldoc.Save(filePath);
            }
            catch (Exception ex)
            {
                tb.AppendText("Error occure when updating the RoleManifest file, program will stopped..." + "\r\n");
                tb.AppendText(ex + "\r\n");
                throw new Exception("custom");
            }
            finally
            {
                tb.Focus();
                tb.Select(tb.TextLength, 0);
                tb.ScrollToCaret();
            }
        }
    }
}
